﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PMS.XCMG.Entity;
using PMS.XCMG.IBusiness;
using PMS.XCMG.Util;
using PMS.XCMG.Models;

namespace PMS.XCMG.Business
{
    public class MaterialBomBusiness : BusRepository<MaterialBom>, IMaterialBomBusiness, IScopedDependency
    {
        private IServiceProvider SvcProvider { get; set; }
        public MaterialBomBusiness(GDbContext context, IServiceProvider svcProvider)
            : base(context)
        {
            this.SvcProvider = svcProvider;
        }

        public async Task<PageResult<MaterialBom>> GetPageResultAsync(PageInput<MaterialBomQM> query)
        {
            var queryable = this.GetQueryable(true);
            queryable = queryable.Include(i => i.Product).Include(i => i.Spec);

            var search = query.Search;
            var result = await this.GetPageResultAsync(queryable, query);
            if (!search.Id.IsNullOrEmpty())
            {
                if (!result.Data.Any(w => w.Id == search.Id))
                {
                    var idOne = await this.GetQueryable(true).SingleOrDefaultAsync(w => w.Id == search.Id);
                    result.Data.Add(idOne);
                    result.Total += 1;
                }
            }
            return result;
        }

        public async Task AssignAsync(string id, string type)
        {
            var now = DateTime.Now;
            var idSvc = this.SvcProvider.GetRequiredService<IIdService>();
            var opSvc = this.SvcProvider.GetRequiredService<IOperator>();
            var curUserId = opSvc.UserId;

            var assignNameType = new List<string>() { "Code", "Name" };
            var assignSpecType = new List<string>() { "Diameter", "Width", "Height", "ToFrockHeight", "SideLength" };

            //找到要下发的记录
            var listSpecAssign = new List<SpecAssign>();
            if (type == "Spec")
                listSpecAssign = await this.GetQueryable<SpecAssign>()
                    .Include(i => i.Bom).Include(i => i.Spec).Include(i => i.AssignDetail)
                    .AsSplitQuery()
                    .Where(w => w.BomId == id && assignSpecType.Contains(w.AssignType))
                    .ToListAsync();
            else
                listSpecAssign = await this.GetQueryable<SpecAssign>()
                    .Include(i => i.Bom).Include(i => i.Spec).Include(i => i.AssignDetail)
                    .AsSplitQuery()
                    .Where(w => w.BomId == id && assignNameType.Contains(w.AssignType))
                    .ToListAsync();
            //生成下发数据
            foreach (var item in listSpecAssign)
            {
                var assign = item.AssignDetail.Select(s => new PlcAssign()
                {
                    Id = idSvc.GetId(),
                    Name = $"{now.ToString("yyyy-MM-dd HH:mm:ss")}-{item.Spec.Name}({item.Bom.Version})",
                    Type = $"{type}Assign",
                    Group = now.Ticks.ToString(),
                    Seq = listSpecAssign.IndexOf(item),
                    PlcIp = s.PlcIp,
                    LogAddr = s.LogAddr,
                    Value = item.Spec.GetPropertyValue(item.AssignType).ToString(),
                    RefTable = nameof(SpecAssignDetail),
                    RefId = s.Id,
                    Status = "Active",
                    AssignTime = DateTime.MinValue,
                    FailCount = 0,
                    Msg = "",
                    CreateTime = now,
                    ModifyTime = now,
                    CreateUserId = curUserId,
                    ModifyUserId = curUserId
                }).ToList();
                await this.DbContext.AddRangeAsync(assign);
            }
            await this.DbContext.SaveChangesAsync();
        }
    }
}
